package zgrjb.snbq.teach_platform.controller;

import com.google.code.kaptcha.Producer;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import zgrjb.snbq.teach_platform.dto.model.User;
import zgrjb.snbq.teach_platform.dto.model.UserDO;
import zgrjb.snbq.teach_platform.dto.req.LoginRequest;
import zgrjb.snbq.teach_platform.dto.req.RegisterRequest;
import zgrjb.snbq.teach_platform.dto.req.SendCodeRequest;
import zgrjb.snbq.teach_platform.enums.BizCodeEnum;
import zgrjb.snbq.teach_platform.enums.SendCodeEnum;
import zgrjb.snbq.teach_platform.interceptor.LoginInterceptor;
import zgrjb.snbq.teach_platform.service.UserService;
import zgrjb.snbq.teach_platform.util.CommonUtil;
import zgrjb.snbq.teach_platform.util.JsonData;
import zgrjb.snbq.teach_platform.util.JwtUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/api/v1/user")
@Slf4j
public class UserController {

    @Autowired(required = false)
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    private static final long CAPTCHA_CODE_EXPIRED = 1000 * 10 * 60;

    /**
     * 获取图形验证码
     */
    @GetMapping("notify")
    public void getNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 检查验证码生成器是否可用
            if (captchaProducer == null) {
                log.warn("验证码生成器未配置，返回简单的数字验证码图片");
                generateSimpleCaptcha(request, response);
                return;
            }

            // 设置响应头
            response.setContentType("image/jpeg");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            
            String captchaText = captchaProducer.createText();
            log.info("验证码内容:{}", captchaText);

            // 存储redis,配置过期时间
            String key = getCaptchaKey(request);
            redisTemplate.opsForValue().set(key, captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
            log.info("验证码已存储到Redis: key={}", key);

            BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

            try (ServletOutputStream outputStream = response.getOutputStream()) {
                ImageIO.write(bufferedImage, "jpg", outputStream);
                outputStream.flush();
                log.info("验证码图片已生成并发送");
            } catch (IOException e) {
                log.error("获取流出错:{}", e.getMessage());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            log.error("生成验证码失败: {}", e.getMessage(), e);
            // 尝试生成简单验证码作为降级方案
            try {
                generateSimpleCaptcha(request, response);
            } catch (Exception ex) {
                log.error("降级验证码生成也失败: {}", ex.getMessage(), ex);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }

    /**
     * 生成简单的数字验证码（降级方案）
     */
    private void generateSimpleCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成4位数字验证码
        String captchaText = String.valueOf((int)(Math.random() * 9000) + 1000);
        log.info("简单验证码内容:{}", captchaText);

        // 存储到Redis
        String key = getCaptchaKey(request);
        redisTemplate.opsForValue().set(key, captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        log.info("简单验证码已存储到Redis: key={}", key);

        // 设置响应头
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 创建简单的验证码图片
        BufferedImage image = new BufferedImage(120, 40, BufferedImage.TYPE_INT_RGB);
        java.awt.Graphics2D g = image.createGraphics();
        
        // 设置背景色
        g.setColor(java.awt.Color.WHITE);
        g.fillRect(0, 0, 120, 40);
        
        // 设置字体
        g.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, 20));
        g.setColor(java.awt.Color.BLACK);
        
        // 绘制验证码文字
        g.drawString(captchaText, 20, 25);
        
        // 添加干扰线
        g.setColor(java.awt.Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = (int)(Math.random() * 120);
            int y1 = (int)(Math.random() * 40);
            int x2 = (int)(Math.random() * 120);
            int y2 = (int)(Math.random() * 40);
            g.drawLine(x1, y1, x2, y2);
        }
        
        g.dispose();

        try (ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
            log.info("简单验证码图片已生成并发送");
        }
    }

    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "account-service:captcha:" + CommonUtil.MD5(ip + userAgent);
        log.info("验证码key:{}", key);
        return key;
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("sendCode")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {
        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        String captcha = sendCodeRequest.getCaptcha();
        if (captcha != null && cacheCaptcha != null && cacheCaptcha.equalsIgnoreCase(captcha)) {
            redisTemplate.delete(key);
            JsonData jsonData = userService.sendCode(SendCodeEnum.ATTENDEE_USER_REGISTER, sendCodeRequest.getPhone());
            return jsonData;
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("register")
    public JsonData register(@RequestBody RegisterRequest request) {
        JsonData jsonData = userService.register(request);
        return jsonData;
    }

    /**
     * 用户登录
     */
    @PostMapping("login")
    public JsonData login(@RequestBody LoginRequest request) {
        JsonData jsonData = userService.login(request);
        return jsonData;
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("info")
    public JsonData getUserInfo() {
        User currentUser = LoginInterceptor.getCurrentUser();
        if (currentUser != null) {
            return JsonData.buildSuccess(currentUser);
        }
        return JsonData.buildError("用户信息不存在");
    }

    /**
     * 用户登出
     */
    @PostMapping("logout")
    public JsonData logout(HttpServletResponse response) {
        try {
            // 清除cookie中的token
            JwtUtil.clearTokenFromCookie(response);
            return JsonData.buildSuccess("登出成功");
        } catch (Exception e) {
            return JsonData.buildError("登出失败");
        }
    }

    /**
     * 通过学号/工号/姓名搜索用户公开信息
     */
    @GetMapping("/public-profile")
    public JsonData getPublicProfile(@RequestParam("keyword") String keyword) {
        // 只返回公开字段
        UserDO user = null;
        // 优先工号
        user = userService.getUserByTeacherNo(keyword);
        if (user == null) {
            // 学号
            user = userService.getUserByStudentId(keyword);
        }
        if (user == null) {
            // 姓名模糊
            user = userService.getUserByName(keyword);
        }
        if (user == null) {
            return JsonData.buildError("未找到用户");
        }
        // 构建公开资料
        Map<String, Object> profile = new HashMap<>();
        profile.put("name", user.getName());
        profile.put("teacherNo", user.getTeacherNo());
        profile.put("department", user.getDepartment());
        profile.put("email", user.getEmail());
        profile.put("headImg", user.getHeadImg());
        profile.put("phone", user.getPhone());
        profile.put("bio", user.getTitle()); // 用title字段临时做简介
        return JsonData.buildSuccess(profile);
    }
}
